<template>
	<view class="container">
		<!--轮播图.开始-->
		<view class="goods-head">
			<swiper circular indicator-dots class="swiper-box">
				<swiper-item v-for="(item,index) in model.goodsAlbums" :key="index">
					<view class="swiper-item">
						<image mode="widthFix" :src="$api.loadFile(item.originalPath)"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<!--轮播图.结束-->

		<button class="shareBtn" type="default" data-name="shareBtn" open-type="share">
			分享
		</button>

		<!--标题.开始-->
		<view class="group-box">
			<view class="goods-title">
				<text class="title">{{model.title}}</text>
				<text class="subtitle">{{model.subTitle}}</text>
				<view class="time" v-if="speedProduct">
					<text>离活动结束还有:</text>
					<uni-countdown :day="speedProduct.countDown.d" :hour="speedProduct.countDown.h"
						:minute="speedProduct.countDown.m" :second="speedProduct.countDown.s">
					</uni-countdown>
				</view>
				<view class="time" v-else-if="presellProduct">
					<text>离活动结束还有:</text>
					<uni-countdown :day="presellProduct.countDown.d" :hour="presellProduct.countDown.h"
						:minute="presellProduct.countDown.m" :second="presellProduct.countDown.s">
					</uni-countdown>
				</view>
				<view v-if="presellProduct" class="label-box">
					<view class="label">
						<text class="tip">流程</text>
						<text>1.支付定金 2.支付尾款 3.活动结束{{presellProduct.deliveryDay}}天发货</text>
					</view>
					<view class="label">
						<text class="tip">尾款支付时段</text>
						<text>{{presellProduct.payStartTime}} - {{presellProduct.payEndTime}}</text>
					</view>
				</view>
				<view class="price">
					<text class="sale" v-if="speedProduct">{{speedProduct.price}}</text>
					<text class="sale" v-else-if="presellProduct">{{presellProduct.totalPrice}}</text>
					<text class="sale" v-else>{{skuProduct?skuProduct.sellPrice:model.sellPrice}}</text>
					<text class="original">{{skuProduct?skuProduct.marketPrice:model.marketPrice}}</text>
					<text v-if="speedProduct" class="tip">限时抢购</text>
					<text v-else-if="presellProduct" class="tip">商品预售</text>
					<text v-if="presellProduct" class="tip">定金{{presellProduct.frontAmount}}元
						尾款{{presellProduct.retainAmount}}元</text>
				</view>
				<view class="info">
					<text>销量：{{model.saleCount}}</text>
					<text>库存：{{model.stockQuantity}}</text>
					<text>浏览量：{{model.click}}</text>
				</view>
			</view>
		</view>
		<!--标题.结束-->

		<!--选项.开始-->
		<view class="group-box">
			<view class="item-list">
				<view class="list-box" @click="openPopup('popSku')">
					<text class="title">规格</text>
					<text class="remark opt">{{skuProduct?'已选 '+skuProduct.skuText:'请选择规格'}}</text>
				</view>
				<view v-if="couponList&&couponList.length>0" class="list-box" @click="openPopup('popTicket')">
					<text class="title">优惠券</text>
					<text class="remark opt">领取优惠券</text>
				</view>
				<view v-if="model.fieldValues" class="list-box" @click="openPopup('popField')">
					<text class="title">参数</text>
					<text class="remark opt">查看商品参数</text>
				</view>
				<view v-if="promotionList.length>0" class="list-box">
					<text class="title">活动</text>
					<view class="remark">
						<text v-for="(item,index) in promotionList" :key="index" class="txt">{{item.title}}</text>
					</view>
				</view>
			</view>
		</view>
		<!--选项.结束-->

		<!--评价.开始-->
		<view class="group-box">
			<view class="ntitle">
				<view class="left">
					<text class="h3">评价({{model.evaluateCount}})</text>
				</view>
				<view class="right">
					<navigator :url="'../evaluate/list?id='+model.id" class="more">查看全部</navigator>
				</view>
			</view>
			<view class="comment-list">
				<view v-if="evaluateList.length===0" class="nodata">
					商品暂无评价
				</view>
				<!--循环.开始-->
				<view v-for="(item,index) in evaluateList" :key="index" class="list-box">
					<view class="head-box">
						<view class="left">
							<view class="img-box">
								<image mode="widthFix" :src="$api.loadFile(item.member.avatar)"></image>
							</view>
							<view class="meta">
								<text>{{item.userName}}</text>
								<text class="time">{{item.addTime}}</text>
							</view>
						</view>
						<view class="star">
							<text v-for="i in 5" :key="i" class="iconfont"
								:class="i<=item.serviceScore?'icon-star-full':'icon-star'"></text>
						</view>
					</view>
					<view class="content">
						<text>
							{{item.content}}
						</text>
					</view>
					<view class="album-box">
						<view v-for="(pic,pindex) in item.evaluateAlbums" :key="pindex" class="img-box">
							<image @click="viewImage(item.evaluateAlbums,pindex)" mode="widthFix"
								:src="$api.loadFile(pic.thumbPath)"></image>
						</view>
					</view>
					<view class="remark">
						<text>{{item.orderGoods.skuText}}</text>
					</view>
				</view>
				<!--循环.结束-->
			</view>
		</view>
		<!--评价.结束-->

		<!--详情.开始-->
		<view class="group-box wrap">
			<view class="goods-detail">
				<view class="stitle">
					<text class="title">商品介绍</text>
				</view>
				<view class="content" v-html="model.content">
				</view>
			</view>
		</view>
		<!--详情.结束-->

		<!--选择规格.开始-->
		<uni-popup ref="popSku" type="bottom">
			<view class="goods-sku">
				<view class="head-box">
					<view class="left">
						<view class="img-box">
							<image mode="widthFix"
								:src="$api.loadFile(skuProduct&&skuProduct.imgUrl?skuProduct.imgUrl:model.imgUrl)">
							</image>
						</view>
					</view>
					<view class="right">
						<view class="item">
							<text class="price" v-if="speedProduct">{{speedProduct.price}}</text>
							<text class="price" v-else-if="presellProduct">{{presellProduct.totalPrice}}</text>
							<text class="price" v-else>{{skuProduct?skuProduct.sellPrice:model.sellPrice}}</text>
						</view>
						<view class="item">
							<text>{{skuProduct?'已选 '+skuProduct.skuText:'请选择规格'}}</text>
						</view>
					</view>
					<view @click="closePopup('popSku')" class="close iconfont icon-close"></view>
				</view>
				<scroll-view scroll-y class="list-wrap">
					<!--循环.开始-->
					<view v-for="(item,index) in skuList" :key="index" class="item-box">
						<text class="title">{{item.title}}</text>
						<view class="list-box">
							<view v-for="(citem,cindex) in item.children" :key="cindex"
								:class="{img:citem.imgUrl, active:citem.selected}" class="item"
								@click="selectSku(item.children, citem)">
								<view v-if="citem.imgUrl" class="img-box">
									<image mode="widthFix" :src="$api.loadFile(citem.imgUrl)"></image>
								</view>
								<text class="txt">{{citem.title}}</text>
							</view>
						</view>
					</view>
					<!--循环.结束-->
					<view class="num-box">
						<view class="title">数量(库存:{{skuProduct?skuProduct.stockQuantity:model.stockQuantity}})</view>
						<view v-if="!speedProduct" class="btn-box">
							<text @click="addQuantity(-1)" class="btn iconfont icon-open"></text>
							<text class="num">{{skuProduct?skuProduct.quantity:1}}</text>
							<text @click="addQuantity(1)" class="btn iconfont icon-add"></text>
						</view>
					</view>
				</scroll-view>
				<view class="foot-box">
					<button v-if="!!speedProduct" @click="addOrder" class="btn">立即抢购</button>
					<button v-else-if="!!presellProduct" @click="addOrder" class="btn">支付定金</button>
					<button v-else @click="addCart" class="btn">加入购物车</button>
				</view>
			</view>
		</uni-popup>
		<!--选择规格.结束-->

		<!--优惠券.开始-->
		<uni-popup ref="popTicket" type="bottom">
			<view class="goods-ticket">
				<view class="head-box">
					<view class="stitle">
						<text class="title">优惠券</text>
					</view>
				</view>
				<scroll-view scroll-y class="list-wrap">
					<view v-for="(item,index) in couponList" :key="index" class="list-box">
						<view class="left">
							<text class="price">{{item.amount}}</text>
						</view>
						<view class="center">
							<text class="title">{{item.title}}</text>
							<text class="time">有效期至{{item.endTime}}</text>
						</view>
						<view class="right">
							<text class="btn" @click="addCoupon(item.id)">立即领取</text>
						</view>
					</view>
				</scroll-view>
				<view class="foot-box">
					<button @click="closePopup('popTicket')" class="btn">关闭</button>
				</view>
			</view>
		</uni-popup>
		<!--优惠券.结束-->

		<!--参数.开始-->
		<uni-popup ref="popField" type="bottom">
			<view class="goods-field">
				<view class="head-box">
					<view class="stitle">
						<text class="title">商品参数</text>
					</view>
				</view>
				<scroll-view scroll-y class="list-wrap">
					<view v-for="(item,index) in model.fieldValues" :key="index" class="list-box">
						<text class="title">{{item.optionName}}</text>
						<text class="note">{{item.optionValue}}</text>
					</view>
				</scroll-view>
				<view class="foot-box">
					<button @click="closePopup('popField')" class="btn">关闭</button>
				</view>
			</view>
		</uni-popup>
		<!--参数.结束-->

		<!--底部.开始-->
		<view class="goods-bar">
			<view class="foot-box">
				<view class="left">
					<navigator :url="'../merchant/index?id='+model.merchantId" class="icon iconfont icon-home-plain">店铺
					</navigator>
					<navigator open-type="switchTab" url="../account/cart" class="icon iconfont icon-cart">购物车
					</navigator>
					<text v-if="isFavorite" class="active icon iconfont icon-star-full">已收藏</text>
					<text v-else class="icon iconfont icon-star" @click="addFavorite(model.id)">收藏</text>
				</view>
				<view class="right">
					<text v-if="!speedProduct&&!presellProduct" @click="addCart" class="btn yellow">加入购物车</text>
					<text v-if="!speedProduct&&!presellProduct" @click="addOrder" class="btn red">立即购买</text>
					<text v-if="!!speedProduct" @click="addOrder" class="btn red">立即抢购</text>
					<text v-if="!!presellProduct" @click="addOrder" class="btn red">支付定金</text>
				</view>
			</view>
		</view>
		<!--底部.结束-->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isFavorite: false, //是否收藏
				couponList: [], //优惠券列表
				promotionList: [], //活动列表
				evaluateList: [], //评价列表
				skuList: [], //商品规格
				speedProduct: null, //限时抢购
				presellProduct: null, //预售商品
				skuProduct: null, //已选中货品
				//商品信息
				model: {
					merchantId: 0,
					goodsProducts: [],
					goodsAlbums: [],
					fieldValues: []
				},
			};
		},
		methods: {
			//打开弹窗
			openPopup(obj) {
				this.$refs[obj].open();
			},
			//关闭弹窗
			closePopup(obj) {
				this.$refs[obj].close();
			},
			//选中规格
			selectSku(list, val) {
				let _this = this;
				//取消同级选中
				list.forEach(item => {
					_this.$set(item, 'selected', false);
				});
				//选中自身
				_this.$set(val, 'selected', true);
				//查找出已选中的货品
				_this.filterProduct();
			},
			//查找选中的货品
			async filterProduct(load = false) {
				let _this = this;
				let skuIds = [];
				_this.skuList.forEach(item => {
					var obj = item.children.find(val => val.selected);
					if (obj) {
						skuIds.push(obj.skuId);
					}
				});
				_this.skuProduct = _this.model.goodsProducts.find(val => val.skuIds.split(',').map(Number).sort()
					.toString() == skuIds.sort().toString());
				_this.$set(_this.skuProduct, 'quantity', 1);
				//查找限时抢购信息
				await _this.$api.request({
					url: `/client/shop/speed/product/${_this.skuProduct.id}`,
					loading: load
				}).then(res => {
					_this.speedProduct = res.data;
					_this.speedProduct.countDown = _this.timeCount(_this.speedProduct.endTime);
				}).catch(err => {
					_this.speedProduct = null;
				});
				//查找商品预售信息
				if (_this.speedProduct == null) {
					await _this.$api.request({
						url: `/client/shop/presell/product/${_this.skuProduct.id}`,
						loading: load
					}).then(res => {
						_this.presellProduct = res.data;
						_this.presellProduct.countDown = _this.timeCount(_this.presellProduct.actEndTime);
					}).catch(err => {
						_this.presellProduct = null;
					});
				}
			},
			//初始化数据
			async initData(id, pid) {
				let _this = this;
				//正在加载
				uni.showLoading({
					title: '加载中'
				});
				//加载商品信息
				await _this.$api.request({
					url: `/client/shop/goods/${id}`,
					method: "get",
				}).then(res => {
					//赋值给商品信息
					_this.model = res.data;
					//替换内容标签
					_this.model.content = _this.$api.replaceHtml(_this.model.content);
					//console.log(_this.model.content);
					//赋值给规格列表
					_this.skuList = _this.model.goodsSkus.filter(val => val.parentId === 0);
					_this.skuList.forEach(item => {
						item.children = _this.model.goodsSkus.filter(val => val.parentId === item
							.skuId);
					});
					//如果指定选中规格
					if (pid && pid > 0) {
						//查找货品
						let productModel = _this.model.goodsProducts.find(val => val.id === pid);
						if (productModel) {
							let skuIds = productModel.skuIds.split(',').map(Number);
							_this.skuList.forEach(item => {
								for (let citem of item.children) {
									for (let sid of skuIds) {
										if (citem.skuId === sid) {
											_this.$set(citem, 'selected', true);
											break;
										}
									}
								}
							});
						}
					}
					//默认选中第一个规格
					else {
						_this.skuList.forEach(item => {
							for (let citem of item.children) {
								if (citem.parentId === item.skuId) {
									_this.$set(citem, 'selected', true);
									break;
								}
							}
						});
					}
					//查找出已选中的货品
					_this.filterProduct();
				}).catch(err => {
					console.log(err);
				});
				//加载评价列表
				await _this.$api.request({
					url: `/client/goods/evaluate/view/${_this.model.id}/1`,
				}).then(res => {
					_this.evaluateList = res.data;
				});
				//加载优惠券列表
				await _this.$api.request({
					url: `/client/shop/coupon/view/10?merchantId=${_this.model.merchantId}`,
				}).then(res => {
					_this.couponList = res.data;
				});
				//加载活动列表
				await _this.$api.request({
					url: `/client/shop/promotion/view/10?merchantId=${_this.model.merchantId}`,
					method: "get",
				}).then(res => {
					_this.promotionList = res.data;
					//console.log(_this.promotionList)
				});
				//加载商品收藏信息
				await _this.$api.request({
					url: `/account/member/favorite/goods/${_this.model.id}`,
					method: "get",
				}).then(res => {
					_this.isFavorite = true;
				}).catch(err => {
					//console.log(err)
				});
				//关闭加载
				uni.hideLoading();
			},
			//计算剩余时间
			timeCount(endTime) {
				let date = new Date();
				let now = date.getTime(); //获得当前时间与1970年1月1日时间相差的毫秒数
				let endDate = new Date(endTime.replace(/-/g, '/'));
				let end = endDate.getTime(); //结束时间与1970年1月1日时间相差的毫秒数
				let leftTime = end - now; //计算两日期之间相差的毫秒数
				let countDown = {};
				if (leftTime >= 0) {
					countDown.d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
					countDown.h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
					countDown.m = Math.floor(leftTime / 1000 / 60 % 60);
					countDown.s = Math.floor(leftTime / 1000 % 60);
				}
				//console.log(countDown)
				return countDown;
			},
			//添加商品收藏
			async addFavorite(goodsId) {
				let _this = this;
				await _this.$api.request({
					url: `/account/member/favorite`,
					method: "post",
					data: {
						siteId: _this.$site,
						goodsId: goodsId
					}
				}).then(res => {
					_this.isFavorite = true;
					uni.showToast({
						title: '收藏成功',
						icon: 'success',
						duration: 2000
					});
				});
			},
			//领取优惠券
			async addCoupon(couponId) {
				let _this = this;
				await _this.$api.request({
					url: `/account/shop/coupon/add`,
					method: "post",
					data: {
						couponId: couponId
					}
				}).then(res => {
					uni.showToast({
						title: '领取成功',
						icon: 'success',
						duration: 2000
					});
				});
			},
			//购物车增减
			addQuantity(num) {
				let _this = this;
				if (num > 0 && _this.skuProduct && _this.skuProduct.quantity < _this.skuProduct.stockQuantity) {
					_this.skuProduct.quantity++;
				}
				if (num < 0 && _this.skuProduct && _this.skuProduct.quantity > 1) {
					_this.skuProduct.quantity--;
				}
				//强制更新视图
				_this.$forceUpdate();
			},
			//加入购物车
			async addCart() {
				let _this = this;
				if (!_this.skuProduct) {
					_this.openPopup('popSku');
					return;
				}
				await _this.$api.request({
					url: `/account/shop/cart`,
					method: "post",
					loading: true,
					data: {
						productId: _this.skuProduct.id,
						quantity: _this.skuProduct.quantity
					}
				}).then(res => {
					_this.closePopup('popSku');
					uni.showToast({
						title: '加入购物车成功',
						icon: 'success',
						duration: 2000
					});
				});
			},
			//立即购买
			addOrder() {
				let _this = this;
				//检查是否已选规格
				if (!_this.skuProduct) {
					_this.openPopup('popSku');
					return;
				}
				//是否抢购商品
				if (_this.speedProduct && _this.speedProduct.id) {
					uni.navigateTo({
						url: `/pages/order/confirm?type=1&id=${_this.speedProduct.id}`
					})
				}
				//是否预售商品
				else if (_this.presellProduct && _this.presellProduct.id) {
					uni.navigateTo({
						url: `/pages/order/confirm?type=2&id=${_this.presellProduct.id}`
					})
				}
				//普通商品
				else {
					//组合已选规格货口
					let goodsData = [];
					goodsData.push({
						productId: _this.skuProduct.id,
						quantity: _this.skuProduct.quantity
					})
					uni.navigateTo({
						url: `/pages/order/confirm?type=0&data=${JSON.stringify(goodsData)}`
					})
				}
			},
			//查看图片
			viewImage(albumList, index) {
				console.log(index)
				let _this = this;
				let urls = albumList.map(item => {
					return _this.$api.loadFile(item.originalPath);
				});
				uni.previewImage({
					urls: urls,
					current: index
				})
			},
		},
		//发送给微信好友
		onShareAppMessage(res) {
			console.log("分享：from:" + res.from);
			return {
				title: this.model.title, //分享的名称
				path: '/pages/goods/show?id='+this.model.id, //页面的路径
			}
		},
		//分享到朋友圈
		onShareTimeline(res) {
			return {
				title: this.model.title,
				type: 0,
				path: '/pages/goods/show?id='+this.model.id,
				imageUrl: this.model.imageUrl,
			}
		},
		//页面初始化
		onLoad(options) {
			let id = parseInt(options.id);
			let productId = 0;
			if (options.pid) {
				productId = parseInt(options.pid);
			}
			this.initData(id, productId);

			//设置Menus菜单，使 发送给朋友/分享到朋友圈 两个按钮可以使用
			wx.showShareMenu({
				withShareTicket: true,
				menus: ["shareAppMessage", "shareTimeline"]
			})
		}
	}
</script>

<style lang="scss">
	.goods-head {
		.swiper-box {
			width: 750rpx;
			height: 750rpx;
			background: #fff;

			.swiper-item {
				display: flex;
				align-items: center;

				image {
					width: 100%;
				}
			}
		}
	}

	.goods-sku {
		box-sizing: border-box;
		padding: 24rpx;
		background: #fff;
		border-radius: 20rpx 20rpx 0 0;

		.head-box {
			display: flex;
			justify-content: flex-start;

			.left {
				position: relative;
				width: 190rpx;

				.img-box {
					box-sizing: border-box;
					border: 2rpx solid rgba($color: #000, $alpha: 0.05);
					border-radius: 20rpx;
					box-shadow: 0 0 4rpx rgba($color: #000, $alpha: 0.1);
					overflow: hidden;
					width: 168rpx;
					height: 168rpx;
					position: absolute;
					top: -68rpx;
					left: 0;
					background: #fff;

					image {
						width: 100%;
					}
				}
			}

			.right {
				.item {
					margin-bottom: 20rpx;
					color: #999;
					font-size: 24rpx;
					line-height: 1;

					.price {
						color: #ff0000;
						font-size: 36rpx;

						&::before {
							content: "￥";
							font-size: 24rpx;
						}
					}
				}
			}

			.close {
				position: absolute;
				top: 12rpx;
				right: 12rpx;
				width: 60rpx;
				height: 60rpx;
				line-height: 60rpx;
				color: #999;
				font-size: 36rpx;
				text-align: center;
			}
		}

		.list-wrap {
			margin: 24rpx 0;
			max-height: calc(100vh - 450rpx);

			.item-box {
				.title {
					display: block;
					color: #999;
					font-size: 28rpx;
					line-height: 64rpx;
				}

				.list-box {
					margin-left: -20rpx;
					word-wrap: break-word;
					display: inline-flex;
					justify-content: flex-start;
					flex-flow: row wrap;

					.item {
						margin: 0 0 20rpx 20rpx;
						border: 2rpx solid #f7f8fa;
						border-radius: 10rpx;
						overflow: hidden;

						.img-box {
							display: flex;
							align-items: center;
							width: 156rpx;
							height: 156rpx;

							image {
								width: 100%;
							}
						}

						.txt {
							display: block;
							padding: 10rpx 24rpx;
							min-width: 80rpx;
							color: #333;
							font-size: 26rpx;
							line-height: 40rpx;
							text-align: center;
							background: #f7f8fa;
							white-space: nowrap;
							text-overflow: ellipsis;
							overflow: hidden;
						}

						&.img {
							width: 156rpx;

							.txt {
								padding: 10rpx;
							}
						}

						&.active {
							border-color: #f63434;

							.txt {
								color: #f63434;
								background: #fff;
							}
						}
					}
				}
			}

			.num-box {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 10rpx 0 24rpx 0;

				.title {
					color: #999;
					font-size: 28rpx;
					line-height: 56rpx;
				}

				.btn-box {
					display: flex;
					justify-content: flex-start;
					line-height: 40rpx;

					.btn {
						color: #333;
						font-size: 24rpx;
						padding: 10rpx 20rpx;
						border-radius: 10rpx;
						background: #f7f8fa;
					}

					.num {
						padding: 10rpx 20rpx;
						color: #333;
						font-size: 28rpx;
					}
				}
			}
		}

		.foot-box {
			.btn {
				padding: 24rpx 30rpx;
				color: #fff;
				font-size: 28rpx;
				line-height: 1;
				border-radius: 50rpx;
				background: #ff0036;

				&::after {
					border: none;
				}
			}
		}
	}

	.goods-field {
		box-sizing: border-box;
		padding: 24rpx;
		background: #fff;
		border-radius: 20rpx 20rpx 0 0;

		.list-wrap {
			margin: 24rpx 0;
			max-height: calc(100vh - 450rpx);
			border: 2rpx solid rgba($color: #000, $alpha: 0.05);
			border-radius: 20rpx;
			overflow: hidden;

			.list-box {
				display: flex;
				justify-content: space-between;
				margin-top: -2rpx;
				border-top: 2rpx solid rgba($color: #000, $alpha: 0.05);
				font-size: 28rpx;
				line-height: 40rpx;

				.title {
					padding: 20rpx 12rpx;
					border-right: 2rpx solid rgba($color: #000, $alpha: 0.05);
					color: #999;
					width: 20%;
					text-align: center;
					white-space: nowrap;
					text-overflow: ellipsis;
					overflow: hidden;
				}

				.note {
					padding: 20rpx 12rpx;
					width: 80%;
					color: #1f1f1f;
				}
			}

			.nodata {
				height: 90rpx;
				line-height: 90rpx;
				color: #999;
				font-size: 28rpx;
				text-align: center;
			}
		}

		.foot-box {
			.btn {
				padding: 24rpx 30rpx;
				color: #fff;
				font-size: 28rpx;
				line-height: 1;
				border-radius: 50rpx;
				background: #ff5000;

				&::after {
					border: none;
				}
			}
		}
	}
</style>